package com.study.mybatis.binding;

import com.study.mybatis.common.CommonCons;
import com.study.mybatis.mapping.MappedStatement;
import com.study.mybatis.session.SqlSession;
import com.sun.org.apache.bcel.internal.generic.RET;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Optional;

import static com.study.mybatis.common.CommonCons.SqlType.SELECT;

/**
 * @author yuantongqin
 * 2021/7/31
 **/
public class MapperProxy<T> implements InvocationHandler {


    SqlSession sqlSession;
    private Class<T> interfaces;

    public MapperProxy(SqlSession sqlSession, Class<T> interfaces) {
        this.sqlSession = sqlSession;
        this.interfaces = interfaces;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            if (Object.class.equals(method.getDeclaringClass())) {
                return method.invoke(this, args);
            }

            return this.executor(method, args);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

    public Object executor(Method method, Object[] args) {
        String statementId = this.interfaces.getName() + "." + method.getName();
        MappedStatement mapper = sqlSession.getConfig().getMapper(statementId);

        Object result = null;
        switch (mapper.getSqlCommandType()) {
            case SELECT:
                Class<?> returnType = method.getReturnType();
                if (Collection.class.isAssignableFrom(returnType)) {
                    result = sqlSession.selectList(mapper.getSql(), args);
                } else {
                    result = sqlSession.selectOne(statementId, args);
                }
            default:
                break;
        }
        return result;
    }

}
